package com.pets.service.Impl;

import com.pets.dao.PhonecodeMapper;
import com.pets.entity.Phonecode;
import com.pets.service.PhonecodeService;
import com.pets.util.sms.SmsSendUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class PhonecodeServiceImpl implements PhonecodeService {

    @Autowired
    private PhonecodeMapper phonecodeDao;
    @Override
    public void sendPhoneCode(String phone) {
        //创建一个随机数对象
        Random random = new Random();

        //产生六位数的随机数字符串
        String code = "" + random.nextInt(9) + random.nextInt(9) + random.nextInt(9) +
                random.nextInt(9) + random.nextInt(9) + random.nextInt(9);

        //调用发送短信的方法
        String msg="【流浪动物救助系统】您的验证码是"+code+"。在3分钟内有效。如非本人操作，请忽略本短信。";
         SmsSendUtil.sendSms(phone, msg);
        //短信发送成功，将发送的数据暂存数据库
        Phonecode phoneCode = new Phonecode(phone, code);
        //调用添加验证码信息的方法
        phonecodeDao.insertSelective(phoneCode);

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //设置三分钟休眠，三分钟后如果短信验证码信息还存在将其删除
                    Thread.sleep(180000);
                    //根据手机号查询PhoneCode表中是否还存在该手机号的验证码信息
                    Phonecode phonecode = phonecodeDao.selectPhoneCodeByPhoneAndCode(phone,code);

                    if(phonecode!=null) {
                        //存在该手机号的验证码信息，将其删除
                        phonecodeDao.deletePhoneCodeByPhone(phone,code);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();


       /* try {
            //设置三分钟休眠，三分钟后如果短信验证码信息还存在将其删除
            Thread.sleep(180000);
            //根据手机号查询PhoneCode表中是否还存在该手机号的验证码信息
            Phonecode phonecode=phonecodeDao.selectPhoneCodeByPhoneAndCode(phone,code);

            if(phoneCode!=null) {
                //存在该手机号的验证码信息，将其删除
                phonecodeDao.deletePhoneCodeByPhone(phone,code);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
    }
}
